package com.hckj.jianzhijia;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.hckj.jianzhijia.controllers.RegisterInfoController;
import com.hckj.jianzhijia.listeners.OnBackClickListener;
import com.hckj.jianzhijia.model.City;
import com.hckj.jianzhijia.model.CompanyUser;
import com.hckj.jianzhijia.model.Province;
import com.hckj.jianzhijia.model.Region;
import com.hckj.jianzhijia.networks.GetCityNetWork;
import com.hckj.jianzhijia.networks.GetProvinceNetWork;
import com.hckj.jianzhijia.networks.GetRegionNetWork;
import com.hckj.jianzhijia.popupwindows.PublishPopupWindowCity;
import com.hckj.jianzhijia.popupwindows.PublishPopupWindowProvince;
import com.hckj.jianzhijia.popupwindows.PublishPopupWindowRegion;
import com.hckj.jianzhijia.utils.ExceptionUtils;
import com.hckj.jianzhijia.utils.MyActivityManager;
import com.hckj.jianzhijia.utils.SharedPreferencesUtil;
import com.hckj.jianzhijia.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class RegisterInfoActivity extends BaseActivity
            implements PublishPopupWindowCity.PublishPopWinCityInterface,
                                   PublishPopupWindowProvince.PublishPopWinProvinceInterface,
                                   PublishPopupWindowRegion.PublishPopWinRegionInterface,
                                   GetCityNetWork.NetWorkInterface,
                                   GetProvinceNetWork.NetWorkInterface,
                                   GetRegionNetWork.NetWorkInterface {

    @InjectView(R.id.imgv_go_back)
    ImageView imgvGoBack;
    @InjectView(R.id.rl_toolbar)
    RelativeLayout rlToolbar;
    @InjectView(R.id.edt_company_name)
    EditText edtCompanyName;
    @InjectView(R.id.edt_email)
    EditText edtEmail;
    @InjectView(R.id.ll_choose_province)
    LinearLayout llChooseProvince;
    @InjectView(R.id.ll_choose_city)
    LinearLayout llChooseCity;
    @InjectView(R.id.ll_choose_area)
    LinearLayout llChooseArea;
    @InjectView(R.id.btn_commit)
    Button btnCommit;
    @InjectView(R.id.edt_address)
    EditText edtAddress;
    @InjectView(R.id.ll_parent)
    LinearLayout llParent;
    @InjectView(R.id.tv_choose_province)
    TextView tvChooseProvince;
    @InjectView(R.id.tv_choose_city)
    TextView tvChooseCity;
    @InjectView(R.id.tv_choose_region)
    TextView tvChooseRegion;

    private RegisterInfoController registerInfoController;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private PublishPopupWindowCity publishPopupWindowCity;
    private PublishPopupWindowProvince publishPopupWindowProvince;
    private PublishPopupWindowRegion publishPopupWindowRegion;

    private ProgressDialog loadingDialog;

    private String companyName;
    private String companyEmail;
    private String companyDetailAddress;
    private String phoneNum;
    private String password;

    private int cityId = -1;
    private int provinceId = -1;
    private int regionId = -1;

    private GetProvinceNetWork getProvinceNetWork;
    private GetCityNetWork getCityNetWork;
    private GetRegionNetWork getRegionNetWork;
    private boolean netWorIsOn = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_info);
        ButterKnife.inject(this);
        phoneNum = getIntent().getStringExtra("phoneNum");
        password = getIntent().getStringExtra("password");
        loadingDialog = new ProgressDialog(this);
        loadingDialog.setCancelable(false);
        loadingDialog.setMessage("正在注册");
        registerInfoController = new RegisterInfoController(this);
        sharedPreferencesUtil = new SharedPreferencesUtil(this);
        initEvent();

    }



    private void initEvent() {

        tvChooseProvince.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(netWorIsOn){
                    return;
                }
                cityId = -1;
                regionId = -1;
                tvChooseCity.setText("地区");
                tvChooseRegion.setText("城市");
                netWorIsOn = true;
                getProvinceNetWork = new GetProvinceNetWork(RegisterInfoActivity.this);
                getProvinceNetWork.execute();
            }
        });

        tvChooseCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(netWorIsOn){
                    return;
                }
                regionId = -1;
                tvChooseRegion.setText("城市");
                if (provinceId == -1) {
                    ToastUtils.showToast(getApplicationContext(), "请选择国别");
                    return;
                } else {
                    netWorIsOn = true;
                    getCityNetWork = new GetCityNetWork(provinceId, RegisterInfoActivity.this);
                    getCityNetWork.execute();
                }
            }
        });

        tvChooseRegion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(netWorIsOn){
                    return;
                }
                if (provinceId == -1) {
                    ToastUtils.showToast(getApplicationContext(), "请选择国别");
                    return;
                } else if (cityId == -1) {
                    ToastUtils.showToast(getApplicationContext(), "请选择地区");
                    return;
                } else {
                    netWorIsOn = true;
                    getRegionNetWork = new GetRegionNetWork(cityId, RegisterInfoActivity.this);
                    getRegionNetWork.execute();
                }
            }
        });


        imgvGoBack.setOnClickListener(new OnBackClickListener(this));

        btnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDataFromEdt();
                if (!registerInfoController.checkAllData(companyName, companyEmail, companyDetailAddress)) {
                    return;
                } else {
                    loadingDialog.show();
                    //注册代码
                    CompanyUser companyUser = new CompanyUser();
                    companyUser.setPhone(phoneNum);
                    companyUser.setPassword(password);
                    companyUser.setName(companyName);
                    companyUser.setEmail(companyEmail);
                    companyUser.setCompanyAddress(companyDetailAddress);
                    companyUser.setCityId(cityId);
                    companyUser.setProvinceId(provinceId);
                    companyUser.setRegionId(regionId);
                    companyUser.registerAvUser().saveInBackground(new SaveCallback() {
                        @Override
                        public void done(AVException e) {
                            if (e == null) {
                                ToastUtils.showToast(getApplicationContext(), "注册成功");
                                loadingDialog.setMessage("正在登陆");
                                LoginNetTask loginNetTask = new LoginNetTask();
                                loginNetTask.execute();
                            } else {
                                ToastUtils.showToast(getApplicationContext(), ExceptionUtils.getExceptionInfo(e));
                                loadingDialog.dismiss();
                            }
                        }
                    });
                }
            }
        });
    }

    private void getDataFromEdt() {
        companyName = edtCompanyName.getText().toString().trim();
        companyEmail = edtEmail.getText().toString().trim();
        companyDetailAddress = edtAddress.getText().toString().trim();
    }


    @Override
    public void setCity(int position, String itemName) {
        this.cityId = position;
        tvChooseCity.setText(itemName);
    }

    @Override
    public void setProvince(int position, String itemName) {
        this.provinceId = position;
        tvChooseProvince.setText(itemName);
    }

    @Override
    public void setRegion(int position, String itemName) {
        this.regionId = position;
        tvChooseRegion.setText(itemName);
    }

    @Override
    public void afterGetProvinces(ArrayList<Province> provinces) {
        netWorIsOn = false;
        if(provinces==null){
            ToastUtils.showToast(getApplicationContext(),"网络错误，无法获取国别列表");
            return;
        }else if(provinces.size() == 0){
            ToastUtils.showToast(getApplicationContext(),"国别列表为空");
            return;
        }

        publishPopupWindowProvince = PublishPopupWindowProvince.newInstance(this, this, llParent, provinces);
        publishPopupWindowProvince.showAtLocation(llParent, Gravity.CENTER, 0, 0);
    }

    @Override
    public void afterGetCities(ArrayList<City> cities) {
        netWorIsOn = false;
        if(cities==null){
            ToastUtils.showToast(getApplicationContext(),"网络错误，无法获取地区列表");
            return;
        }else if(cities.size() == 0){
            ToastUtils.showToast(getApplicationContext(),"地区列表为空");
            return;
        }

        publishPopupWindowCity = PublishPopupWindowCity.newInstance(this, this, llParent, cities);
        publishPopupWindowCity.showAtLocation(llParent, Gravity.CENTER, 0, 0);
    }

    @Override
    public void afterGetRegions(ArrayList<Region> regions) {
        netWorIsOn = false;
        if(regions==null){
            ToastUtils.showToast(getApplicationContext(),"网络错误，无法获取城市列表");
            return;
        }else if(regions.size() == 0){
            ToastUtils.showToast(getApplicationContext(),"城市列表为空");
            return;
        }

        publishPopupWindowRegion = PublishPopupWindowRegion.newInstance(this, this, llParent, regions);
        publishPopupWindowRegion.showAtLocation(llParent, Gravity.CENTER, 0, 0);
    }

    private class LoginNetTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                AVUser avUser = AVUser.logIn(phoneNum, password);
                avUser.getAVObject("userInfo").fetchIfNeeded();
                jianzhijiaApplacation.setCompanyUser(new CompanyUser(avUser));
                AVQuery provinceQuery = new AVQuery(Province.TABLE_NAME);
                AVQuery cityQuery = new AVQuery(City.TABLE_NAME);
                AVQuery regionQuery = new AVQuery(Region.TABLE_NAME);
                provinceQuery.whereEqualTo("provinceId", jianzhijiaApplacation.getCompanyUser().getProvinceId());
                cityQuery.whereEqualTo("cityId",jianzhijiaApplacation.getCompanyUser().getCityId());
                regionQuery.whereEqualTo("regionId", jianzhijiaApplacation.getCompanyUser().getRegionId());

                List provinceList =  provinceQuery.find();
                List cityList =  cityQuery.find();
                List regionList =  regionQuery.find();

                if(provinceList.size()!=0){
                    jianzhijiaApplacation.getCompanyUser().setProvinceName(new Province((AVObject)(provinceList.get(0))).getProvince());
                }

                if(cityList.size()!=0){
                    jianzhijiaApplacation.getCompanyUser().setCityName(new City((AVObject) (cityList.get(0))).getCity());
                }

                if(regionList.size()!=0){
                    jianzhijiaApplacation.getCompanyUser().setRegionName(new Region((AVObject) (regionList.get(0))).getRegion());
                }

                sharedPreferencesUtil.setAutoLogin(true);
                sharedPreferencesUtil.setCurrentUserPhonePassword(phoneNum, password);
                return null;
            } catch (AVException e) {
                e.printStackTrace();
                return ExceptionUtils.getExceptionInfo(e);
            }
        }

        @Override
        protected void onPostExecute(String aVoid) {
            if (aVoid == null) {
                loadingDialog.dismiss();
                ToastUtils.showToast(getApplicationContext(), "登录成功");
                MyActivityManager.getInstance().finishAllActivity();
                startActivity(new Intent(getApplicationContext(), MainActivity.class));
            } else {
                loadingDialog.dismiss();
                ToastUtils.showToast(getApplicationContext(), aVoid);
            }
            super.onPostExecute(aVoid);
        }
    }
}
